'use strict';

/**
 * @ngdoc function
 * @name webApp.controller:UsertableCtrl
 * @description
 * # UsertableCtrl
 * Controller of the webApp
 */

angular.module('webApp')
  .controller('userTable', function ($scope,cookie,promiseUserTable,popBox,$location) {
    var userTables = [
      {
        userTableName: '个人信息',
        butImg: 'butImg1',
        point: false,
        userTableSref: 'root.userData'
      },
      {
        userTableName: '我的评论',
        butImg: 'butImg2',
        point: false,
        userTableSref: 'root.userCommunicate'
      },
      {
        userTableName: '我的收藏',
        butImg: 'butImg3',
        point: false,
        userTableSref: 'root.userCollection'
      },
      {
        userTableName: '我的消息',
        butImg: 'butImg4',
        point: false,
        userTableSref: 'root.userInformation'
      }
    ];
    $scope.userTables = userTables;
    var point = ''; //历史md5
    $scope.$on('$stateChangeSuccess',function(){
      //已登录
      if(cookie.getCookie('access_token')){
        promiseUserTable.userInformations(1,10).then(function(data){
          //md5检测
          var newData = md5(JSON.stringify(data));
          if(point != newData && point != ''){
            $scope.userTables[3].point = true;
          }
          else{
            $scope.userTables[3].point = false;
          }
          point = newData;
        });
        $scope.signOutShow = true;
        //退出登录
        $scope.signIn = false;
        $scope.signOut = function(){
          //后端操作
          if(cookie.getCookie('access_token')){
            promiseUserTable.signOut();
          }
          cookie.delCookie('access_token');
          $scope.signOutShow = false;
          $scope.userName = '用户登录';
          $scope.userHead = 'images/userOriginHead.png' + '?' + Math.random();
          for(var i = 0;i < userTables.length;i++){
            userTables[i].point = false;
          }
          popBox.showConfirm('提示','退出登录成功！');
        };
        promiseUserTable.getUserData().then(function(data){
          if(data.avatar_url == "/uploads/images/avatar/default.png"){
            $scope.userHead = 'images/userOriginHead.png' + '?' + Math.random();
          }
          else{
            $scope.userHead = data.avatar_url + '?' + Math.random();
          }
          if(data.name == ''){
            $scope.userName = data.email;
          }
          else{
            $scope.userName = data.name;
          }
        });
      }
      //未登录
      else{
        $scope.signOutShow = false;
        $scope.userName = '用户登录';
        $scope.userHead = 'images/userOriginHead.png' + '?' + Math.random();
        $scope.userTables = userTables;
      }
    });
    $scope.signInPage = function(){
      if(!cookie.getCookie('access_token')){
        $location.path('/root/signIn');
      }
    };
});
